<script lang="ts">
export default {
  name: 'manage',
};
</script>

<script lang="ts" setup>

import {onMounted, reactive, ref} from 'vue';

import RepositoryProductTable from './components/RepositoryProductTable.vue';
import RepositoryProductDetail from './components/RepositoryProductDetail.vue';


import {formatDate,} from '@/utils/formatter';

import {getEntity} from "@/api/device/product";
import {RepoProductEntity} from "@/api/device/product/types";
import {CreateRepositoryRequestVO} from "@/api/repo/comp/cloud/file/types";
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteCloudEntity, downloadCloudEntity, installCloudEntity} from "@/api/repo/comp/cloud/file";
import {restartDeviceService} from "@/api/repo/comp/local/jar-file";


const repositoryProductTableRef = ref<any>(); // 这了的变量名称必须和<deviceDecoder-edit-dialog>的ref值一样
const repositoryProductDetailRef = ref<any>(); // 这了的变量名称必须和<deviceDecoder-edit-dialog>的ref值一样

const dataState = reactive({
  productId: '',
  entity: {} as RepoProductEntity,
});

function getSelect(source: string, type: string, row: any) {
  let selects = [] as any;
  if (source === 'table') {
    if (row.lastVersion !== undefined) {
      selects.push(row.lastVersion);
    } else {
      selects.push(row);
    }

  }
  if (source === 'header') {
    let rows = repositoryProductTableRef.value.getSelects();
    if (rows.length === 0) {
      return;
    }

    for (let row of rows) {
      if (row.lastVersion !== undefined) {
        selects.push(row.lastVersion);
      }
    }
  }

  return selects;
}

/**
 * 响应查询按钮：页查询数据
 */
function handleRestart(source: string) {
  ElMessageBox.confirm('确认重启设备服务?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    restartDeviceService().then(() => {
      ElMessage.success('重启设备服务成功');
    });
  })
    .catch(() => ElMessage.info('已取消重启设备服务'));
}

/**
 * 捕获下载对话框消息
 * @taskParam source 发出消息的数据来源：button/table
 * @taskParam type 操作类型：delete
 * @taskParam row 行信息
 */
function handleDownload(source: string, type: string, row: any) {
  let selects = getSelect(source, type, row) as any;

  if (selects.length === 0) {
    return;
  }

  let services = [] as any;
  for (let version of selects) {
    let data = {} as CreateRepositoryRequestVO;
    data.modelType = version.modelType;
    data.modelName = version.modelName;
    data.modelVersion = version.modelVersion;
    data.version = version.version;
    data.stage = version.stage;
    data.component = version.component;
    data.pathName = version.pathName;
    services.push(data);
  }

  ElMessageBox.confirm('确认下载已选中的数据项的安裝包?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    downloadCloudEntity(services).then(() => {
      ElMessage.success('添加下载任务成功');
      // 刷新表单
      handleQuery();
    });
  })
    .catch(() => ElMessage.info('已取消下载'));
}


function handleInstall(source: string, type: string, row: any) {
  let selects = getSelect(source, type, row) as any;

  if (selects.length === 0) {
    return;
  }

  let version = selects[0];
  let data = {} as CreateRepositoryRequestVO;
  data.modelType = version.modelType;
  data.modelName = version.modelName;
  data.modelVersion = version.modelVersion;
  data.version = version.version;
  data.stage = version.stage;
  data.component = version.component;
  data.pathName = version.pathName;


  ElMessageBox.confirm('确认下载已选中的数据项的安裝包?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    installCloudEntity(data).then(() => {
      ElMessage.success('安装成功！');
      // 刷新表单
      handleQuery();
    });
  })
    .catch(() => ElMessage.info('已取消安装'));
}

/**
 * 捕获删除对话框消息
 * @taskParam source 发出消息的数据来源：button/table
 * @taskParam type 操作类型：delete
 * @taskParam row 行信息
 */
function handleDelete(source: string, type: string, row: any) {
  let selects = getSelect(source, type, row) as any;

  if (selects.length === 0) {
    return;
  }

  let services = [] as any;
  for (let version of selects) {
    let data = {} as CreateRepositoryRequestVO;
    data.modelType = version.modelType;
    data.modelName = version.modelName;
    data.modelVersion = version.modelVersion;
    data.version = version.version;
    data.stage = version.stage;
    data.component = version.component;
    data.pathName = version.pathName;
    services.push(data);
  }

  ElMessageBox.confirm('确认清理已选中的数据项的缓存?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteCloudEntity(services).then(() => {
      ElMessage.success('删除成功');

      // 刷新表单
      handleQuery();
    });
  })
    .catch(() => ElMessage.info('已取消删除'));
}

/**
 * 刷新页面信息
 */
function handleQuery() {
  getEntity(dataState.productId).then(({data}) => {
    data.imageUrl = "http://repository.fox-tech.cn/image/" + data.image;
    data.updateTimeText = formatDate(data.updateTime);

    for (let value of data.comps) {
      for (let version of value.versions) {
        version.modelName = value.modelName;
        version.modelType = value.modelType;
        version.modelVersion = value.modelVersion;
      }

      value.lastVersion.modelType = value.modelType;
      value.lastVersion.modelName = value.modelName;
      value.lastVersion.modelVersion = value.modelVersion;

    }

    dataState.entity = data;
    repositoryProductDetailRef.value.initEditData(data);
    repositoryProductTableRef.value.refreshTable(data);
  });

}

function getUuidFromHref() {
  let tag = "/repo-comp/cloud/repo-comp-product-detail?uuid=";
  let start = location.href.indexOf(tag);
  if (start > 0) {
    return location.href.substring(start + tag.length);
  }

  return '';
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  // 从地址栏获得产品ID
  dataState.productId = getUuidFromHref();

  // 向后台查询详细信息
  handleQuery();
});

</script>

<template>
  <div class="app-container">

    <!-- 表单头：各种按钮 -->
    <repository-product-detail ref="repositoryProductDetailRef"
                               @query="handleQuery"
                               @restart="handleRestart"
    />


    <!-- 数据表单：创建/修改 -->
    <repository-product-table ref="repositoryProductTableRef"
                              @delete="handleDelete"
                              @download="handleDownload"
                              @install="handleInstall"
    />

  </div>
</template>
